package com.czsth.home.repositories;

import com.mongodb.*;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

import java.util.Arrays;

/**
 * Created by bruce on 2015/3/17.
 */
public class Repositories {

    final MongoClientOptions options = MongoClientOptions.builder()
            .socketKeepAlive(true) // 是否保持长链接
            .heartbeatFrequency(1000 * 30)//
            .connectTimeout(5000) // 链接超时时间
            .socketTimeout(5000) // read数据超时时间
            .readPreference(ReadPreference.primary()) // 最近优先策略
            .connectionsPerHost(30) // 每个地址最大请求数
            .maxWaitTime(1000 * 60 * 2) // 长链接的最大等待时间
            .threadsAllowedToBlockForConnectionMultiplier(50) // 一个socket最大的等待请求数
            .writeConcern(WriteConcern.NORMAL)
            .build();

    final MongoClient mongo = new MongoClient(new ServerAddress("114.215.81.46", 27017), Arrays.asList(
            MongoCredential.createCredential("bao", "buru", "12345678".toCharArray()),
            MongoCredential.createCredential("buru", "admin", "buru.mongodb".toCharArray())
    ), options);

    final MongoDatabase database = mongo.getDatabase("buru");

    public MongoCollection<Document> collection(String collectionName) {
        return database.getCollection(collectionName);
    }

    public static Repositories singleton() {
        //TODO 还不是singleton
        return new Repositories();
    }
}
